package com.dream.common.websocket;

import cn.hutool.json.JSONUtil;
import com.dream.common.websocket.domain.enums.WSReqTypeEnum;
import com.dream.common.websocket.domain.vo.req.WSBaseReq;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;


@Slf4j
@Sharable
public class NettyWebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {



    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        String text = msg.text();
        WSBaseReq wsBaseReq = JSONUtil.toBean(text, WSBaseReq.class);

        switch (WSReqTypeEnum.of(wsBaseReq.getType())) {
            case LOGIN:
                System.out.println("请求登录二维码");
                ctx.channel().writeAndFlush(new TextWebSocketFrame("dream"));
                break;
            case AUTHORIZE:
                break;
            case HEARTBEAT:
                break;

        }
        System.out.println(text);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
            System.out.println("握手成功");
            //有的时候握手后需要进行认证操作
        } else if (evt instanceof IdleStateEvent) {  //读空闲事件，一般是服务端设置的，当超过我们设定的时间过后还没有收到前端的心跳包，就会触发这个事件，此时我们要让用户下线
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {

                //todo 用户下线 连接关闭
                ctx.channel().close();

            }
        }

        super.userEventTriggered(ctx, evt);
    }
}
